package Gridview;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.table.DefaultTableModel;

import JDBC.SqlHelper;

public class JtableTest extends JFrame implements ActionListener {
	private JTable table;
	private JScrollPane scrollpane;
	private DefaultTableModel tableModel; // 表格模型对象
	final JButton addButton,updateButton,delButton;
	final JPanel panel;
	public JtableTest()
	{
		setTitle("学生信息管理");
		tableModel = new DefaultTableModel();
		tableModel.addColumn("学号");
		tableModel.addColumn("姓名");
		tableModel.addColumn("年龄");
		tableModel.addColumn("QQ");
		tableModel.addColumn("Email");
		table = new JTable(tableModel);
		table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); // 单选
		final JLabel lab=new JLabel();
		table.addMouseListener(new MouseAdapter() { // 鼠标事件
			public void mouseClicked(MouseEvent e) {
				int selectedRow = table.getSelectedRow(); // 获得选中行索引
				if(selectedRow!=-1){lab.setText("当前选中行："+selectedRow);}
				//Object oa = tableModel.getValueAt(selectedRow, 0);
				//Object ob = tableModel.getValueAt(selectedRow, 1);
				
			}
		});
		scrollpane = new JScrollPane(table); // 支持滚动
		getContentPane().add(scrollpane, BorderLayout.CENTER);
		BindData();
		
		panel = new JPanel();
		addButton = new JButton("添加"); // 添加按钮
		updateButton = new JButton("修改"); // 修改按钮
		delButton = new JButton("删除");
		addButton.addActionListener(this);
		updateButton.addActionListener(this);
		delButton.addActionListener(this);
		panel.add(lab);
		panel.add(addButton);
		panel.add(updateButton);
		panel.add(delButton);
		getContentPane().add(panel, BorderLayout.SOUTH);
		this.setVisible(true);
		this.setBounds(200, 200, 650, 400);
	}
	public void BindData()
	{
        try 
 	   {
 		   ResultSet rs = SqlHelper.Query("select * from Student");
 		   
 		   while(rs.next())
 		   {
 			  tableModel.addRow(new String[]{
 					 rs.getString("StudNo"),
 					  rs.getString("Name"),
 					  String.valueOf(rs.getInt("avg")),
 					  rs.getString("QQ"),
 					  rs.getString("Email")
 					  });
 			   
 		   }
 		   rs.close();
 		  
 	   }
 	   catch (SQLException e) 
 	   {
 		   e.printStackTrace();
 	   }
	}
	
	public void actionPerformed(ActionEvent e) {
		/*if(e.getSource()==selectButton)
		{
		
		}*/
		if(e.getSource()==addButton)
		{
		
		}
		if(e.getSource()==updateButton)
		{
		
		}
		if(e.getSource()==delButton)
		{
		
		}
	}

	public static void main(String[] args) {
		JtableTest test =new JtableTest();

	}

}
